/**
 * @Author: 陈瑞鹏
 * @Date:   2022-11-25 10:24:20
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2023-01-12 09:43:16
 */

import baozhaEle from "../eles/baozhaEle";
import BaseEle, { campType, soliderType } from "../eles/baseEle";
import bulletEle from "../eles/bulletEle";
import circleEle from "../eles/circleEle";
import descComp from "../views/descCom";
import dieEle from "../eles/dieEle";
import gameCtr, { modelType } from "../ctrs/gameCtr";
import lineCom from "../eles/lineCom";
import mouseCom from "../views/mouseCom";
import { SoundResManager } from "../ctrs/soundCtr";
import triangleCom from "../eles/triangleCom";
import arrowEle from "../eles/arrowEle";
import fireBallEle from "../eles/fireBallEle";
import squareCom from "../eles/squareCom";
import frozenEle from "../eles/frozenEle";
import recoverEle from "../eles/recoverEle";
import BaseGameScene from "../libs/core/BaseGameScene";
import { SceneManager } from "../libs/manager/SceneManager";
import barrackEntity from "../ctrs/barracks/barrackEntity";
import barrackCtr from "../ctrs/barracks/barrackCtr";
import snowEle from "../eles/snowEle";
import treasureCtr from "../ctrs/treasure/treasureCtr";
import exchangeTp from "../ctrs/treasure/exchangeTp";
import netCtr from "../ctrs/netCtr";
import treasureTp from "../ctrs/treasure/treasureTp";
import dcEle from "../eles/dcEle";
import robotPvpCtr from "../ctrs/pvp/robotPvpCtr";
import { PlayerState } from "../shared/game/state/PlayerState";
import { getTimehms } from "../libs/core/utils";

//人机对战
const { ccclass, property } = cc._decorator;

@ccclass
export default class robotWarScene extends BaseGameScene {

  @property({ type: cc.Node, tooltip: "鼠标节点" })
  mouseNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "元素节点" })
  eleNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "资源节点" })
  resNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "buff节点" })
  effectNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "圈的节点" })
  circleNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "兵营列表" })
  barracks: cc.Node = null;

  @property({ type: cc.Node, tooltip: "描述节点" })
  descNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "金币" })
  goldTxt: cc.Label = null;

  @property({ type: cc.Prefab, tooltip: "加农炮预制体" })
  cannonPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "子弹预制体" })
  bulletPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "火球预制体" })
  fireBallPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "雪花预制体" })
  snowPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "箭预制体" })
  arrowPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "地雷预制体" })
  shellPre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "子弹层" })
  bulletNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "是否结束" })
  overNode: cc.Node = null;

  @property({ type: cc.Prefab, tooltip: "死亡" })
  diePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "爆炸" })
  baozhaPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "地刺" })
  dcPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "冰冻" })
  frozenPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "回复" })
  recoverPre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "血迹层" })
  bloodLayer: cc.Node = null;

  @property({ type: cc.Node, tooltip: "ready" })
  readyNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "三角圆形" })
  triNode: cc.Node = null;

  @property({ type: cc.Prefab, tooltip: "地雷预制体" })
  dlPre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "不能生成区域遮罩" })
  pmNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "左边用户昵称" })
  leftNickName: cc.Label = null;

  @property({ type: cc.Sprite, tooltip: "左边头像" })
  leftAvatar: cc.Sprite = null;

  @property({ type: cc.Label, tooltip: "左边金币" })
  leftGoldTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "房间号" })
  roomTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "右边用户昵称" })
  rightNickName: cc.Label = null;

  @property({ type: cc.Sprite, tooltip: "右边头像" })
  rightAvatar: cc.Sprite = null;

  @property({ type: cc.Label, tooltip: "右边金币" })
  rightGoldTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "准备开始描述" })
  readyTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "倒计时" })
  downTimeTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "描述一" })
  txt1: cc.Label = null;

  @property({ type: cc.Label, tooltip: "描述二" })
  txt2: cc.Label = null;

  @property({ type: cc.Label, tooltip: "描述一" })
  txt11: cc.Label = null;

  @property({ type: cc.Label, tooltip: "描述二" })
  txt22: cc.Label = null;

  public monsterTime: any = false;

  public isPause: boolean = false; //是否暂停

  public timeHandler = null;

  public castleSpr: BaseEle = null; //城堡脚本

  onLoad() {
    super.onLoad();
    gameCtr.ins.curScene = this.node;
    gameCtr.ins.resNode = this.resNode;
    gameCtr.ins.effectNode = this.effectNode;
    gameCtr.ins.eleNode = this.eleNode;
    gameCtr.ins.gameModel = modelType.pvp;

    SoundResManager.getInstance().preload("sound");

    this.node.on("die", this.onCreateDie, this);
    this.node.on("fireBullet", this.createBullet, this);
    this.node.on("fireSnow", this.createSnow, this);
    this.node.on("fireBall", this.createBall, this);
    this.node.on("fireArrow", this.createArrow, this);
    this.node.on("baozha", this.onCreateBaozha, this);
    this.node.on("dc", this.onCreateDc, this);
    this.node.on("doShell", this.createShell, this);
    this.node.on("frozen", this.doCreateFrozen, this);
    this.node.on("recover", this.doCreateRecover, this);

    this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onMove, this);
    this.node.on(cc.Node.EventType.MOUSE_MOVE, this.onMove, this);
    this.node.on(cc.Node.EventType.TOUCH_END, this.onUp, this);
    this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onUp, this);
    this.node.on(cc.Node.EventType.MOUSE_UP, this.onUp, this);

    gameCtr.ins.initPool("die", 20, this.diePre);
    gameCtr.ins.initPool("bullet", 10, this.bulletPre);
    gameCtr.ins.initPool("snow", 10, this.snowPre);
    gameCtr.ins.initPool("cannon", 10, this.cannonPre);
    gameCtr.ins.initPool("baozha", 10, this.baozhaPre);
    gameCtr.ins.initPool("dc", 10, this.dcPre);
    gameCtr.ins.initPool("shell", 10, this.shellPre);
    gameCtr.ins.initPool("dl", 10, this.dlPre);
    gameCtr.ins.initPool("arrow", 10, this.arrowPre);
    gameCtr.ins.initPool("fireBall", 10, this.fireBallPre);
    gameCtr.ins.initPool("frozen", 5, this.frozenPre);
    gameCtr.ins.initPool("recover", 5, this.recoverPre);

    let childs = this.barracks.children;
    for (let i = 0; i < childs.length; i++) {

      if (gameCtr.ins.barracksArr[i]) {
        childs[i].on(cc.Node.EventType.TOUCH_START, this.onBarrckDown, this);

        cc.resources.load(gameCtr.ins.barracksArr[i].iconUrl, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
          childs[i].getComponentInChildren(cc.Sprite).spriteFrame = sp;
        })
      } else {
        childs[i].getComponentInChildren(cc.Sprite).spriteFrame = null;
      }
    }

    let playerState: PlayerState = {
      id: gameCtr.ins.roleId,
      //昵称
      nickName: gameCtr.ins.nickName,
      //头像
      avatar: gameCtr.ins.avatar,
      //金币数量
      gold: 120,
      //左边右边
      team: 2,
      //房间id
      roomId: gameCtr.ins.roleId + "",
      //房间名称
      roomName: "房间_" + gameCtr.ins.roleId,
      //是否准备
      isReady: false,
      //城堡血量
      hp: 100,
      isRobot: false
    }
    robotPvpCtr.ins.players.set(gameCtr.ins.roleId, playerState);

    let robotState: PlayerState = {
      id: gameCtr.ins.roleId * -1,
      //昵称
      nickName: Math.floor(Math.random() * 100) + Math.floor(Math.random() * 1000) + "",
      //头像
      avatar: gameCtr.ins.avatar,
      //金币数量
      gold: 120,
      //左边右边
      team: 1,
      //房间id
      roomId: gameCtr.ins.roleId + "",
      //房间名称
      roomName: "房间_" + gameCtr.ins.roleId,
      //是否准备
      isReady: true,
      //城堡血量
      hp: 100,
      isRobot: false
    }
    robotPvpCtr.ins.players.set(robotState.id, robotState);

    this.updatePlayer();
  }

  /**
   * 点击准备
   */
  onReady() {
    robotPvpCtr.ins.players.get(gameCtr.ins.roleId).isReady = true;
    this.readyNode.active = false;
    robotPvpCtr.ins.isStart = true;
    let now = new Date().getTime();
    robotPvpCtr.ins.gameOverTime = now + 120000;

    //创建城堡
    let c = cc.instantiate(gameCtr.ins.preObj['castle']);
    let spr = c.getComponent(BaseEle);
    spr.setInfo(gameCtr.ins.castleData);
    c.setPosition(cc.v2(380, 0));
    spr.setZIndex();
    this.eleNode.addChild(c);
    robotPvpCtr.ins.playerBaseEles.push(spr);

    //创建机器人城堡
    c = cc.instantiate(gameCtr.ins.preObj['castle']);
    spr = c.getComponent(BaseEle);
    spr.setInfo(gameCtr.ins.castleData);
    c.setPosition(cc.v2(-380, 0));
    spr.setZIndex();
    spr.campType = campType.enemy;
    this.eleNode.addChild(c);
    robotPvpCtr.ins.robotBaseEles.push(spr);

    this.createPvpRes();

    this.scheduleOnce(() => {
      this.createRobotSp(cc.v2(-380, 170), cc.v2(-200, -80), cc.v2(-520, -100));
    }, 10);

    this.scheduleOnce(() => {
      this.createRobotSp(cc.v2(-240, 100), cc.v2(-300, -120), cc.v2(-520, 0));
    }, 30);

    this.scheduleOnce(() => {
      this.createRobotSp(cc.v2(-140, 0), cc.v2(-270, -180), cc.v2(-520, 100));
    }, 50);

    for (let i = 0; i < 13; i++) {

      this.scheduleOnce(() => {

        this.createRobotGuard();

      }, 5 + i * 12)

      this.scheduleOnce(() => {

        this.createRobotDogs(i % 3);

      }, 2 + i * 10)
    }

    this.schedule(() => {
      if (!robotPvpCtr.ins.isStart) return;
      robotPvpCtr.ins.players.get(gameCtr.ins.roleId * 1).gold += 10;
      robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).gold += 10;
    }, 5)
  }

  /**
   * 创建机器 狗
   */
  createRobotDogs(i) {
    if (robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).gold < 25) return;
    //机器人创建 狗
    let circle = gameCtr.ins.poolObj['circle'].get();
    if (!circle) {
      circle = cc.instantiate(gameCtr.ins.preObj['circle']);
    }
    let arr = [180, 50, -100, -200];
    circle.setPosition(cc.v2(Math.random() * 40 - 20, (Math.random() * 50 - 20) + arr[i]));
    this.circleNode.addChild(circle);

    let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(1);

    circle.getComponent(circleEle).hp = barrackEny.num;

    circle.getComponent(circleEle).drawColor("#FC6B3D");

    robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).gold -= 25;

    for (let i = 0; i < barrackEny.num; i++) {
      this.createDogs(circle, i, -1);
    }
  }

  createRobotSp(pos1, pos2, pos3) {
    if (robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).gold < 55) return;
    let triangle = gameCtr.ins.poolObj['triangle'].get();
    if (!triangle) {
      triangle = cc.instantiate(gameCtr.ins.preObj['triangle']);
    }
    triangle.setPosition(cc.v2(0, 0));
    triangle.getComponent(triangleCom).cirCleColor = "#FC6B3D";
    triangle.getComponent(triangleCom).grapColor = "#FC6B3D";
    triangle.getComponent(triangleCom).isCanMove = false;
    triangle.getComponent(triangleCom).init(pos1, pos2, pos3);
    this.circleNode.addChild(triangle);
    // this.eleNode.addChild(triangle);
    triangle.getComponent(triangleCom).drawGrap();
    let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(2);
    triangle.getComponent(triangleCom).hp = barrackEny.num;
    for (let i = 0; i < barrackEny.num; i++) {
      this.createSpearman(triangle, i, -1);
    }
    robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).gold -= 55;

  }

  /**
  * 创建守卫
  */
  async createRobotGuard() {
    if (robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).gold < 100) return;
    let circle = gameCtr.ins.poolObj['circle3'].get();
    if (!circle) {
      circle = await cc.instantiate(gameCtr.ins.preObj['circle3']);
    }

    circle.getComponent(circleEle).isCanMove = false;
    let pos = cc.v2(Math.random() * 100 - 200, Math.random() * 300 - 150);
    circle.setPosition(pos);
    this.circleNode.addChild(circle);

    let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(3);
    circle.getComponent(circleEle).hp = barrackEny.num;
    circle.getComponent(circleEle).drawColor("#FC6B3D");

    this.scheduleOnce(() => {
      circle.setPosition(cc.v2(380, 0));
    }, 3);
    for (let i = 0; i < barrackEny.num; i++) {
      this.createGuard(circle, i, -1);
    }

    robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).gold -= 100;

  }

  /**
   * 创建资源
   */
  createPvpRes() {

    if (this.resNode.children.length > 0) return;

    let arr = [
      { type: soliderType.mineral, x: -80, y: 180, maxHp: 50, hp: 50, iconUrl: "ele/mineral_1", poolName: "mineral" },
      { type: soliderType.mineral, x: 0, y: 180, maxHp: 50, hp: 50, iconUrl: "ele/mineral_2", poolName: "mineral" },
      { type: soliderType.mineral, x: 80, y: 180, maxHp: 50, hp: 50, iconUrl: "ele/mineral_3", poolName: "mineral" },
      { type: soliderType.tree, x: -40, y: 100, maxHp: 10, hp: 10, iconUrl: "ele/tree_1", poolName: "tree" },
      { type: soliderType.tree, x: 40, y: 100, maxHp: 10, hp: 10, iconUrl: "ele/tree_2", poolName: "tree" },
      { type: soliderType.tree, x: -40, y: 20, maxHp: 10, hp: 10, iconUrl: "ele/tree_3", poolName: "tree" },
      { type: soliderType.tree, x: 40, y: 20, maxHp: 10, hp: 10, iconUrl: "ele/tree_1", poolName: "tree" },
      { type: soliderType.tree, x: -40, y: -60, maxHp: 10, hp: 10, iconUrl: "ele/tree_2", poolName: "tree" },
      { type: soliderType.tree, x: 40, y: -60, maxHp: 10, hp: 10, iconUrl: "ele/tree_3", poolName: "tree" },
      { type: soliderType.mineral, x: -40, y: -140, maxHp: 50, hp: 50, iconUrl: "ele/mineral_1", poolName: "mineral" },
      { type: soliderType.mineral, x: 40, y: -140, maxHp: 50, hp: 50, iconUrl: "ele/mineral_2", poolName: "mineral" },
      { type: soliderType.mineral, x: -80, y: -220, maxHp: 50, hp: 50, iconUrl: "ele/mineral_3", poolName: "mineral" },
      { type: soliderType.mineral, x: 0, y: -220, maxHp: 50, hp: 50, iconUrl: "ele/mineral_1", poolName: "mineral" },
      { type: soliderType.mineral, x: 80, y: -220, maxHp: 50, hp: 50, iconUrl: "ele/mineral_2", poolName: "mineral" },
    ];

    for (let i: number = 0; i < arr.length; i++) {
      let c = gameCtr.ins.poolObj[arr[i].poolName].get();
      if (!c) {
        if (arr[i].poolName == "tree") {
          c = cc.instantiate(gameCtr.ins.preObj['tree']);
        } else if (arr[i].poolName == "mineral") {
          c = cc.instantiate(gameCtr.ins.preObj['tree']);
        } else if (arr[i].poolName == "dl") {
          c = cc.instantiate(gameCtr.ins.preObj['dl']);
        }
      }
      let spr = c.getComponent(BaseEle)
      spr.setInfo(arr[i]);
      spr.initSp(arr[i].iconUrl);
      c.setPosition(cc.v2(arr[i].x, arr[i].y));
      this.resNode.addChild(c);
    }

  }

  /**
  * 更新玩家信息ui
  */
  updatePlayer() {
    if (!robotPvpCtr.ins) return;
    if (!robotPvpCtr.ins.isStart) return;
    //倒计时
    let now = new Date().getTime();
    this.downTimeTxt.string = getTimehms((robotPvpCtr.ins.gameOverTime - now) * 0.001);

    let leftPlayer = robotPvpCtr.ins.players.get(gameCtr.ins.roleId);
    let rightPlayer = robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1);

    if (robotPvpCtr.ins.players.get(gameCtr.ins.roleId).team == 1) {
      leftPlayer = robotPvpCtr.ins.players.get(gameCtr.ins.roleId);
      rightPlayer = robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1);
    } else {
      leftPlayer = robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1);
      rightPlayer = robotPvpCtr.ins.players.get(gameCtr.ins.roleId);
    }

    if (leftPlayer) {
      this.leftNickName.string = `${leftPlayer.nickName.substring(0, 8)}`;
      this.leftGoldTxt.string = `${leftPlayer.gold}`;
      let iconUrl = barrackCtr.ins.getBarrackById(Number(leftPlayer.avatar)).iconUrl;
      cc.resources.load(iconUrl, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
        if (err) return;
        if (this.leftAvatar)
          this.leftAvatar.spriteFrame = sp;
      })
    } else {
      this.leftNickName.string = ``;
      this.leftGoldTxt.string = `0`;
      this.leftAvatar.spriteFrame = null;
    }

    if (rightPlayer) {
      this.rightNickName.string = `${rightPlayer.nickName.substring(0, 8)}`;
      this.rightGoldTxt.string = `${rightPlayer.gold}`;
      let iconUrl = barrackCtr.ins.getBarrackById(Number(rightPlayer.avatar)).iconUrl;
      cc.resources.load(iconUrl, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
        if (err) return;
        if (this.rightAvatar)
          this.rightAvatar.spriteFrame = sp;
      })
    } else {
      this.leftNickName.string = ``;
      this.leftGoldTxt.string = `0`;
      this.leftAvatar.spriteFrame = null;
    }

    let player = leftPlayer || rightPlayer;
    this.roomTxt.string = player && player.roomName;
  }


  /**
   * 创建术士
   */
  async createSnow(pos, targetPos, aoeNum, type: soliderType = soliderType.cannon, campType) {
    // console.log(pos, targetPos);
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['snow'].get();

      if (!node) {
        node = await cc.instantiate(this.snowPre);
      }

      node.setPosition(pos.x, pos.y);
      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(snowEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }

  }
  /**
   * 创建冰冻
   */
  doCreateFrozen(pos, campType) {
    let node = gameCtr.ins.poolObj['frozen'].get();
    if (!node) {
      node = cc.instantiate(this.frozenPre);
    }
    let nPos = gameCtr.ins.effectNode.convertToNodeSpaceAR(pos);
    node.setPosition(nPos);
    node.getComponent(frozenEle).setInfo({
      life: 120,
      campType: campType,
    })
    gameCtr.ins.effectNode.addChild(node);
  }

  /**
   * 创建回复
   */
  async doCreateRecover(pos, targetPos, aoeNum, type: soliderType = soliderType.master) {
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['recover'].get();

      if (!node) {
        node = await cc.instantiate(this.fireBallPre);
      }

      node.setPosition(pos.x, pos.y);

      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(recoverEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }
  }


  /**
   * 创建死亡动画
   */
  async onCreateDie(e) {
    let node = gameCtr.ins.poolObj['die'].get();
    if (!node) {
      node = await cc.instantiate(this.diePre);
    }
    // console.log(e);
    if (!node) return;
    let nPos = this.bloodLayer.convertToNodeSpaceAR(e);
    node.setPosition(nPos);
    // console.log(nPos);
    node.getComponent(dieEle).setInfo();
    this.bloodLayer.addChild(node);
  }

  /**
   * 创建爆炸动画
   */
  async onCreateBaozha(e, aoeNum = 5, campType = 1) {
    let node = gameCtr.ins.poolObj['baozha'].get();
    if (!node) {
      node = await cc.instantiate(this.baozhaPre);
    }
    // console.log(e);
    let nPos = this.bloodLayer.convertToNodeSpaceAR(e);
    node.setPosition(nPos);
    // console.log(nPos);
    node.getComponent(baozhaEle).setInfo({ aoeNum: aoeNum, campType: campType });
    this.bloodLayer.addChild(node);
  }

  /**
   * 创建地刺动画
   */
  async onCreateDc(e, aoeNum = 5, campType = 1) {
    let node = gameCtr.ins.poolObj['dc'].get();
    if (!node) {
      node = await cc.instantiate(this.dcPre);
    }
    // console.log(e);
    // let nPos = this.bloodLayer.convertToNodeSpaceAR(e);
    node.setPosition(e);
    // console.log(nPos);
    node.getComponent(dcEle).setInfo({ aoeNum: aoeNum, campType: campType });
    this.bloodLayer.addChild(node);
  }


  //创建资源
  async createRes() {
    for (let i = 0; i < 4; i++) {
      let c = gameCtr.ins.poolObj[gameCtr.ins.resData[i].poolName].get();
      if (!c) {
        if (gameCtr.ins.resData[i].poolName == "tree") {
          c = await cc.instantiate(gameCtr.ins.preObj['tree']);
        } else if (gameCtr.ins.resData[i].poolName == "mineral") {
          c = await cc.instantiate(gameCtr.ins.preObj['mineral']);
        } else if (gameCtr.ins.resData[i].poolName == "dl") {
          c = await cc.instantiate(this.dlPre);
        }
      }
      let spr = c.getComponent(BaseEle)
      spr.setInfo(gameCtr.ins.resData[i]);
      spr.initSp(gameCtr.ins.resData[i].iconUrl);
      c.setPosition(gameCtr.ins.resData[i].namePos);
      gameCtr.ins.resNode.addChild(c);
    }
  }

  //随机创建资源
  async createRandRes() {
    let r = Math.floor(Math.random() * gameCtr.ins.resData.length);
    let res = gameCtr.ins.resData[r];
    let c = gameCtr.ins.poolObj[res.poolName].get();
    if (!c) {
      if (res.poolName == "tree") {
        c = await cc.instantiate(gameCtr.ins.preObj['tree']);
      } else if (res.poolName == "mineral") {
        c = await cc.instantiate(gameCtr.ins.preObj['mineral']);
      } else if (res.poolName == "dl") {
        c = await cc.instantiate(this.dlPre);
      }
    }
    let spr = c.getComponent(BaseEle)
    spr.setInfo(res);
    spr.initSp(res.iconUrl);
    let n = Math.random() * 380 + 150;
    let x = (Math.random() < 0.5 ? -1 : 1) * n;
    let y = Math.random() * 480 - 240;
    c.setPosition(cc.v2(x, y));
    gameCtr.ins.resNode.addChild(c);
  }

  async doCreateDl() {
    let c = gameCtr.ins.poolObj["dl"].get();
    let res = { iconUrl: "ele/dl", harvest: 0, attack: 0, hp: 30, namePos: cc.v2(-200, 190), poolName: "dl", type: soliderType.dl };
    if (!c) {
      if (res.poolName == "tree") {
        c = await cc.instantiate(gameCtr.ins.preObj['tree']);
      } else if (res.poolName == "mineral") {
        c = await cc.instantiate(gameCtr.ins.preObj['mineral']);
      } else if (res.poolName == "dl") {
        c = await cc.instantiate(this.dlPre);
      }
    }
    let spr = c.getComponent(BaseEle)
    spr.setInfo(res);
    spr.initSp(res.iconUrl);
    let n = Math.random() * 380 + 150;
    let x = (Math.random() < 0.5 ? -1 : 1) * n;
    let y = Math.random() * 480 - 240;
    c.setPosition(cc.v2(x, y));

    gameCtr.ins.dlNum++;
    gameCtr.ins.resNode.addChild(c);
  }

  /**
   * 创建矿工
   * @param circle 
   */
  async createMiner(circle, owner: number = 1) {
    let node = gameCtr.ins.poolObj['miner'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['mineral']);
    }

    let x = Math.random() * 150 - 75;
    let y = Math.random() * 90 - 52;

    node.setPosition(x + circle.x, y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      id: 12,
      attack: 1, harvest: 1, hp: 5, type: soliderType.miner, isCanMove: true,
      poolName: "miner", moveSpeed: 180
    })
    spr.ownerId = gameCtr.ins.roleId * owner;
    spr.centerPos = circle;
  }

  /**
   * 创建守卫
   */
  async createGuard(circle, i, ownerId: number = 1) {
    let node = gameCtr.ins.poolObj['guard'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['guard']);
    }
    let arr = [cc.v2(-20, 35), cc.v2(35, 5)];

    let x = arr[i].x;
    let y = arr[i].y;

    node.setPosition(x + circle.x, y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 1, harvest: 0, hp: 10, type: soliderType.guard, isCanMove: true,
      poolName: "guard", id: 3
    })
    spr.centerPos = circle;
    spr.offX = x;
    spr.offY = y;
    spr.campType = ownerId == 1 ? campType.mine : campType.enemy;
  }

  /**
   * 创建剑士
   * @param circle 
   * @param i 
   */
  async createSwordsman(circle, i) {
    let node = gameCtr.ins.poolObj['swordsman'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['swordsman']);
    }
    let arr = [cc.v2(0, 0), cc.v2(-20, 20), cc.v2(20, 20)];

    node.setPosition(arr[i].x + circle.x, arr[i].y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 1, harvest: 0, hp: 3, type: soliderType.swordsman, isCanMove: true,
      poolName: "swordsman", id: 9
    })
    spr.centerPos = circle;
    spr.offX = arr[i].x;
    spr.offY = arr[i].y;
  }

  /**
  * 创建弓兵
  */
  async createBowman(circle, i) {
    let node = gameCtr.ins.poolObj['bowman'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['bowman']);
    }
    let arr = [cc.v2(0, 0), cc.v2(-25, 25), cc.v2(25, 25), cc.v2(-25, -25), cc.v2(25, -25)];

    node.setPosition(arr[i].x + circle.x, arr[i].y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 1, harvest: 0, hp: 1, type: soliderType.bowman, isCanMove: true,
      poolName: "bowman", id: 8
    })
    spr.centerPos = circle;
    spr.offX = arr[i].x;
    spr.offY = arr[i].y;
  }

  /**
   * 创建骑兵
   * @param circle 
   * @param i 
   */
  async createCavalry(circle, i) {
    let node = gameCtr.ins.poolObj['cavalry'].get();
    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['cavalry']);
    }
    let arr = [cc.v2(25, -25), cc.v2(-25, 25), cc.v2(25, 25), cc.v2(-25, -25)];
    node.setPosition(arr[i].x + circle.x, arr[i].y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 1, harvest: 0, hp: 8, type: soliderType.cavalry, isCanMove: true, id: 10,
      poolName: "cavalry", moveSpeed: 240
    })
    spr.centerPos = circle;
    spr.offX = arr[i].x;
    spr.offY = arr[i].y;
  }

  /**
   * 创建民兵
   */
  async createMilitia(line, i) {
    let posArr = [
      cc.v2(-18, 18,), cc.v2(-18, -18), cc.v2(0, 0),

      cc.v2(18, 18), cc.v2(18, -18),
    ]
    let node: cc.Node = gameCtr.ins.poolObj['militia'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['militia']);
    }
    let spr = line.getComponent(lineCom);
    let pos = this.eleNode.convertToNodeSpaceAR(spr.pos2w);

    node.setPosition(posArr[i].x + pos.x, posArr[i].y + pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.setInfo({
      attack: 1, harvest: 0, hp: 3, type: soliderType.militia, isCanMove: true, poolName: "militia", id: 7
    })
    sprn.centerPos = line;
    sprn.offX = posArr[i].x;
    sprn.offY = posArr[i].y;
    this.eleNode.addChild(node);
  }

  /**
   * 创建盾兵
   */
  async createShield(line, i) {
    let posArr = [
      cc.v2(-13, 13,), cc.v2(-13, -13),

      cc.v2(13, 13), cc.v2(13, -13),
    ]
    let node: cc.Node = gameCtr.ins.poolObj['shield'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['shield']);
    }
    let spr = line.getComponent(lineCom);
    let pos = this.eleNode.convertToNodeSpaceAR(spr.pos2w);

    node.setPosition(posArr[i].x + pos.x, posArr[i].y + pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.setInfo({
      attack: 1, harvest: 0, hp: 10, type: soliderType.shield, id: 4, isCanMove: true, poolName: "shield"
    })
    sprn.centerPos = line;
    sprn.offX = posArr[i].x;
    sprn.offY = posArr[i].y;
    this.eleNode.addChild(node);
  }

  /**
   * 创建枪兵
   */
  async createSpearman(triangle, i, ownerId: number = 1) {

    let posArr = [
      cc.v2(-50, 12.5), cc.v2(-50, -12.5),
      cc.v2(-25, 25,), cc.v2(-25, 0), cc.v2(-25, -25),
      cc.v2(0, 37.5), cc.v2(0, 12.5), cc.v2(0, -12.5), cc.v2(0, -37.5),
      cc.v2(25, 25,), cc.v2(25, 0), cc.v2(25, -25),
    ]
    let node: cc.Node = gameCtr.ins.poolObj['spearman'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['spearman']);
    }
    let spr = triangle.getComponent(triangleCom);
    let pos = this.eleNode.convertToNodeSpaceAR(spr.pos1w);

    node.setPosition(posArr[i].x + pos.x, posArr[i].y + pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.setInfo({
      attack: 1, harvest: 0, hp: 2, type: soliderType.spearman, isCanMove: true, poolName: "spearman", id: 2
    })
    sprn.centerPos = triangle;
    sprn.offX = posArr[i].x;
    sprn.offY = posArr[i].y;
    sprn.campType = ownerId == 1 ? campType.mine : campType.enemy;
    this.eleNode.addChild(node);
  }

  /**
   * 点击
   * @param e 
   */
  onBarrckDown(e) {
    // console.log("onBarrckDown")
    // console.log(e.currentTarget.name)
    gameCtr.ins.selectData = null;
    let data = null;
    switch (e.currentTarget.name) {
      case "item0":
        data = gameCtr.ins.barracksArr[0];
        break;
      case "item1":
        data = gameCtr.ins.barracksArr[1];
        break;
      case "item2":
        data = gameCtr.ins.barracksArr[2];
        break;
      case "item3":
        data = gameCtr.ins.barracksArr[3];
        break;
      case "item4":
        data = gameCtr.ins.barracksArr[4];
        break;
      case "item5":
        data = gameCtr.ins.barracksArr[5];
        break;
      case "item6":
        data = gameCtr.ins.barracksArr[6];
        break;
    }
    let playerState = robotPvpCtr.ins.players.get(gameCtr.ins.roleId);
    if (playerState.gold < data.need) {
      SceneManager.getInstance().pushLayer("tipLayer", "金币不足");
      return; //金币不足
    }
    // if (data == gameCtr.ins.selectData) return;
    gameCtr.ins.selectData = data;
    e.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL);
    e.currentTarget.off(cc.Node.EventType.TOUCH_END);
    // let nowPos: any = e.getLocation();
    // let pos = this.node.convertToNodeSpaceAR(nowPos);

    this.mouseNode.getComponent(mouseCom).drawSp(gameCtr.ins.selectData.iconUrl);
    e.currentTarget.on(cc.Node.EventType.TOUCH_CANCEL, this.onCreateCirle, this);
    e.currentTarget.on(cc.Node.EventType.TOUCH_END, this.onCreateCirle2, this);
  }

  /**
   * 创建
   * @param touch 
   */
  onCreateCirle(touch) {
    touch.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL);
    touch.currentTarget.off(cc.Node.EventType.TOUCH_END);

    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);
    if (pos.x < 0) {
      SceneManager.getInstance().pushLayer("tipLayer", "不能在敌方放置");
      return;
    }
    if (pos.y < -200) {
      gameCtr.ins.selectData = null;
      this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
      return;
    };

    this.doCreate(touch);
  }

  onCreateCirle2(touch) {
    touch.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL);
    touch.currentTarget.off(cc.Node.EventType.TOUCH_END);

    gameCtr.ins.selectData = null;
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
  }

  /**
   * 执行
   * @param touch 
   * @returns 
   */
  async doCreate(touch) {
    if (this.isPause) return;
    if (!gameCtr.ins.selectData) return;
    // touch.currentTarget.off(cc.Node.EventType.TOUCH_START);
    let playerState = robotPvpCtr.ins.players.get(gameCtr.ins.roleId);
    if (playerState.gold < gameCtr.ins.selectData.need) {
      SceneManager.getInstance().pushLayer("tipLayer", "金币不足");
      return; //金币不足
    }
    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);

    if (gameCtr.ins.selectData.poolName == "dogs") {
      let circle = gameCtr.ins.poolObj['circle'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);

      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);

      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(1);

      circle.getComponent(circleEle).hp = barrackEny.num;
      circle.getComponent(circleEle).drawColor("#00DBFF");
      for (let i = 0; i < barrackEny.num; i++) {
        this.createDogs(circle, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "spearman") {
      let triangle = gameCtr.ins.poolObj['triangle'].get();
      if (!triangle) {
        triangle = await cc.instantiate(gameCtr.ins.preObj['triangle']);
      }
      triangle.setPosition(cc.v2(0, 0));
      triangle.getComponent(triangleCom).init(pos, cc.v2(pos.x, pos.y + 120), cc.v2(pos.x + 120, pos.y));
      this.circleNode.addChild(triangle);
      // this.eleNode.addChild(triangle);

      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(2);
      triangle.getComponent(triangleCom).hp = barrackEny.num;
      for (let i = 0; i < barrackEny.num; i++) {
        this.createSpearman(triangle, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "guard") {
      let circle = gameCtr.ins.poolObj['circle3'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle3']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);
      circle.getComponent(circleEle).drawColor("#8F57FC");
      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);
      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(3);
      circle.getComponent(circleEle).hp = barrackEny.num;

      for (let i = 0; i < barrackEny.num; i++) {
        this.createGuard(circle, i);
      }

    } else if (gameCtr.ins.selectData['poolName'] == "shield") {
      let line = gameCtr.ins.poolObj['line'].get();
      if (!line) {
        line = await cc.instantiate(gameCtr.ins.preObj['line']);
      }
      line.setPosition(cc.v2(0, 0));
      line.getComponent(lineCom).init(cc.v2(380, 0), pos);
      this.circleNode.addChild(line);

      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(4);
      line.getComponent(lineCom).hp = barrackEny.num;
      line.getComponent(lineCom).isTwo = false;

      for (let i = 0; i < barrackEny.num; i++) {
        this.createShield(line, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "cannon") {
      let node: cc.Node = gameCtr.ins.poolObj['cannon'].get();

      if (!node) {
        node = await cc.instantiate(this.cannonPre);
      }

      node.setPosition(pos.x, pos.y);
      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(BaseEle);
      sprn.setInfo({
        attack: 1, harvest: 0, hp: 10, type: soliderType.cannon, isCanMove: false, poolName: "cannon", id: 5
      })
      node.zIndex = 999;
      this.eleNode.addChild(node);
    } else if (gameCtr.ins.selectData['poolName'] == "bomb") {
      let a = [cc.v2(80, 0), cc.v2(-80, 0), cc.v2(0, 80), cc.v2(0, -80)];
      this.onCreateBaozha(nowPos, 10, 1);
      this.scheduleOnce(() => {
        a.forEach(ele => {
          this.onCreateBaozha(cc.v2(nowPos.x + ele.x, nowPos.y + ele.y), 10, 1);
        })
      }, 0.1)
    } else if (gameCtr.ins.selectData['poolName'] == "shell") {
      this.createShell(pos);
    } else if (gameCtr.ins.selectData['poolName'] == "militia") {
      let line = gameCtr.ins.poolObj['line'].get();
      if (!line) {
        line = await cc.instantiate(gameCtr.ins.preObj['line']);
      }
      line.setPosition(cc.v2(0, 0));
      line.getComponent(lineCom).init(cc.v2(pos.x, pos.y - 100), pos);
      this.circleNode.addChild(line);

      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(7);
      line.getComponent(lineCom).hp = barrackEny.num;
      line.getComponent(lineCom).isTwo = true;

      for (let i = 0; i < barrackEny.num; i++) {
        this.createMilitia(line, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "bowman") {
      let circle = gameCtr.ins.poolObj['circle3'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle3']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);
      circle.getComponent(circleEle).drawColor("#8F57FC");
      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);
      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(8);
      circle.getComponent(circleEle).hp = barrackEny.num;

      for (let i = 0; i < barrackEny.num; i++) {
        this.createBowman(circle, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "swordsman") {
      let circle = gameCtr.ins.poolObj['circle3'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle3']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);
      circle.getComponent(circleEle).drawColor("#8F57FC");
      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);
      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(9);
      circle.getComponent(circleEle).hp = barrackEny.num;

      for (let i = 0; i < barrackEny.num; i++) {
        this.createSwordsman(circle, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "cavalry") {
      let circle = gameCtr.ins.poolObj['circle'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);
      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);
      circle.getComponent(circleEle).drawColor("#00DBFF");
      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(10);
      circle.getComponent(circleEle).hp = barrackEny.num;
      for (let i = 0; i < barrackEny.num; i++) {
        this.createCavalry(circle, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "trapped") {
      console.log("dddd")
      this.createTrapped(pos);
    } else if (gameCtr.ins.selectData['poolName'] == "miner") {
      let circle = gameCtr.ins.poolObj['circle2'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle2']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);
      circle.getComponent(circleEle).drawColor("#00DBFF");
      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);
      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(12);
      circle.getComponent(circleEle).hp = barrackEny.num;

      for (let i = 0; i < barrackEny.num; i++) {
        this.createMiner(circle);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "master") {
      let circle = gameCtr.ins.poolObj['circle3'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle3']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);
      circle.getComponent(circleEle).drawColor("#8F57FC");
      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);

      circle.getComponent(circleEle).hp = 1;

      this.createMaster(circle);

    } else if (gameCtr.ins.selectData['poolName'] == "fighter") {
      let square = gameCtr.ins.poolObj['square'].get();
      if (!square) {
        square = await cc.instantiate(gameCtr.ins.preObj['square']);
      }
      square.setPosition(cc.v2(0, 0));
      square.getComponent(squareCom).init(pos, cc.v2(pos.x + 120, pos.y), cc.v2(pos.x + 120, pos.y + 120), cc.v2(pos.x, pos.y + 120));
      this.circleNode.addChild(square);
      // this.eleNode.addChild(triangle);
      let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(14);
      square.getComponent(squareCom).hp = barrackEny.num;

      for (let i = 0; i < barrackEny.num; i++) {
        this.createFighter(square, i);
      }
    } else if (gameCtr.ins.selectData['poolName'] == "warlock") {
      // this.doCreateFrozen(pos, campType.mine);
      let circle = gameCtr.ins.poolObj['circle3'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle3']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);
      circle.getComponent(circleEle).drawColor("#8F57FC");
      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);

      circle.getComponent(circleEle).hp = 1;

      this.createWarlock(circle);

    } else if (gameCtr.ins.selectData['poolName'] == "scarecrow") {
      this.createScarecrow(pos);
    } else if (gameCtr.ins.selectData['poolName'] == "jumpFire") {
      this.createJumpFire(pos);
    } else if (gameCtr.ins.selectData['poolName'] == "logistics") {
      let circle = gameCtr.ins.poolObj['circle3'].get();
      if (!circle) {
        circle = await cc.instantiate(gameCtr.ins.preObj['circle3']);
      }
      circle.setPosition(pos);
      this.circleNode.addChild(circle);

      circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);

      circle.getComponent(circleEle).hp = 1;

      this.createLogistics(circle);
    }

    playerState.gold -= gameCtr.ins.selectData.need;
    // this.updateGold();
    gameCtr.ins.selectData = null;
    SoundResManager.getInstance().PlayBGM();
    SoundResManager.getInstance().Play("create");
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
  }

  /**
   * 
   */
  async createJumpFire(pos) {
    let node: cc.Node = gameCtr.ins.poolObj['jumpFire'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['jumpFire']);
    }
    node.setPosition(pos.x, pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.targetPosArr = [cc.v2(-540, 240), cc.v2(-540, -200), cc.v2(540, -200), cc.v2(540, 240)];
    let nodeIndex = 0;
    if (pos.x > 0 && pos.y > 0) {
      nodeIndex = 3;
    } else if (pos.x > 0 && pos.y < 0) {
      nodeIndex = 2;
    }
    else if (pos.x < 0 && pos.y < 0) {
      nodeIndex = 1;
    }
    sprn.setInfo({
      id: 17,
      attack: 1, harvest: 0, hp: 120, type: soliderType.jumpFire, isCanMove: true, poolName: "jumpFire", nodeIndex: nodeIndex
    })
    this.eleNode.addChild(node);
  }

  /**
   * 创建术士
   */
  async createWarlock(circle) {
    let node = gameCtr.ins.poolObj['warlock'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['warlock']);
    }

    let x = Math.random() * 100 - 50;
    let y = Math.random() * 60 - 35;

    node.setPosition(x + circle.x, y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 1, harvest: 0, hp: 1, type: soliderType.warlock, isCanMove: true,
      poolName: "warlock", id: 15
    })
    spr.centerPos = circle;
  }

  /**
   * 创建稻草人
   */
  async createScarecrow(pos) {
    let node: cc.Node = gameCtr.ins.poolObj['scarecrow'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['scarecrow']);
    }

    node.setPosition(pos.x, pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.setInfo({
      attack: 1, harvest: 0, hp: 20, type: soliderType.scarecrow, isCanMove: false, poolName: "scarecrow", id: 16, campType: campType.mine
    })
    this.eleNode.addChild(node);
  }

  /**
   * 创建格斗家
   * @param square 
   * @param i 
   */
  async createFighter(square, i) {
    let posArr = [
      cc.v2(-25, 25,), cc.v2(-25, -25),
      cc.v2(25, 25,), cc.v2(25, -25),
    ]
    let node: cc.Node = gameCtr.ins.poolObj['fighter'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['fighter']);
    }
    let spr = square.getComponent(squareCom);
    let pos = this.eleNode.convertToNodeSpaceAR(spr.pos1w);

    node.setPosition(posArr[i].x + pos.x, posArr[i].y + pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.setInfo({
      id: 14,
      attack: 1, harvest: 0, hp: 10, type: soliderType.fighter, isCanMove: true, poolName: "fighter"
    })
    sprn.centerPos = square;
    sprn.offX = posArr[i].x;
    sprn.offY = posArr[i].y;
    this.eleNode.addChild(node);
  }

  /**
   * 创建医疗兵
   * @param circle 
   */
  async createLogistics(circle) {
    let node = gameCtr.ins.poolObj['logistics'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['logistics']);
    }

    let x = Math.random() * 100 - 50;
    let y = Math.random() * 60 - 35;

    node.setPosition(x + circle.x, y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 1, harvest: 0, hp: 1, type: soliderType.logistics, isCanMove: true,
      poolName: "logistics", id: 18
    })
    spr.centerPos = circle;
  }
  /**
   * 创建法师
   * @param circle 
   * @param i 
   */
  async createMaster(circle) {
    let node = gameCtr.ins.poolObj['master'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['master']);
    }

    let x = Math.random() * 100 - 50;
    let y = Math.random() * 60 - 35;

    node.setPosition(x + circle.x, y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 1, harvest: 0, hp: 2, type: soliderType.master, isCanMove: true,
      poolName: "master", id: 13
    })
    spr.centerPos = circle;
  }

  /**
   * 创建训练犬
   * @param circle 
   * @param i 
   */
  async createDogs(circle, i, owner: number = 1) {
    let node = gameCtr.ins.poolObj['dogs'].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj['dogs']);
    }

    let x = Math.random() * 200 - 100;
    let y = Math.random() * 120 - 70;

    node.setPosition(x + circle.x, y + circle.y);
    this.eleNode.addChild(node);
    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      attack: 0, harvest: 1, hp: 2, type: soliderType.dogs, isCanMove: true,
      poolName: "dogs", id: 1
    })
    spr.campType = owner == 1 ? campType.mine : campType.enemy;
    // console.log(spr.ownerId, "spr.ownerId");
    spr.centerPos = circle;
  }

  /**
   * 创建陷阵骑士
   */
  async createTrapped(pos) {
    let node = gameCtr.ins.poolObj['trapped'].get();
    if (!node) {
      node = cc.instantiate(gameCtr.ins.preObj['trapped']);
    }
    node.setPosition(pos);
    let sprn = node.getComponent(BaseEle);
    let b = (700 / Math.max(Math.abs(pos.y), Math.abs(pos.x)));

    // sprn.targetPosArr = [cc.v2(pos.x * b, pos.y * b)]
    sprn.targetPosArr = [cc.v2(800, pos.y * b)]
    sprn.setInfo({
      id: 11,
      attack: 1, harvest: 0, hp: 100, type: soliderType.trapped, isCanMove: true, poolName: "trapped",
    })
    this.eleNode.addChild(node);
  }

  /**
   * 创建地雷
   * @param pos 
   */
  async createShell(pos = null, wPos = null) {
    let node: cc.Node = gameCtr.ins.poolObj['shell'].get();
    if (!node) {
      node = await cc.instantiate(this.shellPre);
    }
    if (wPos) {
      pos = this.eleNode.convertToNodeSpaceAR(wPos);
    }

    node.setPosition(pos.x, pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.setInfo({
      attack: 1, harvest: 0, hp: 1, type: soliderType.shell, isCanMove: false, poolName: "shell"
    })
    this.eleNode.addChild(node);
  }

  /**
   * 创建火球
   * @param pos 
   * @param targetPos 
   * @param aoeNum 
   * @param type 
   */
  async createBall(pos, targetPos, aoeNum, type: soliderType = soliderType.master) {
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['fireBall'].get();

      if (!node) {
        node = await cc.instantiate(this.fireBallPre);
      }

      node.setPosition(pos.x, pos.y);

      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(fireBallEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }
  }

  /**
   * 创建加农炮 炮弹
   */
  async createBullet(pos, targetPos, aoeNum, type: soliderType = soliderType.cannon, campType) {
    // console.log(pos, targetPos);
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['bullet'].get();

      if (!node) {
        node = await cc.instantiate(this.bulletPre);
      }

      node.setPosition(pos.x, pos.y);
      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(bulletEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }

  }


  /**
   * 创建 箭
   */
  async createArrow(pos, targetPos, aoeNum, type: soliderType = soliderType.cannon, campType) {
    // console.log(pos, targetPos);
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['arrow'].get();

      if (!node) {
        node = await cc.instantiate(this.arrowPre);
      }

      node.setPosition(pos.x, pos.y);
      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(arrowEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }

  }

  /**
   * 点击圆圈
   * @param e 
   */
  onCircleDown(e) {
    e.currentTarget.on(cc.Node.EventType.TOUCH_MOVE, this.onCircleMove, this);
    e.currentTarget.color = new cc.Color().fromHEX("#ffffff");
    // console.log(e.currentTarget);
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorHold");
  }

  /**
   * 移动圆圈
   * @param e 
   */
  onCircleMove(e) {
    let nowPos: any = e.getLocation();
    let pos = this.circleNode.convertToNodeSpaceAR(nowPos);
    e.currentTarget.on(cc.Node.EventType.TOUCH_END, this.onCirCleUp, this);
    e.currentTarget.on(cc.Node.EventType.TOUCH_CANCEL, this.onCirCleUp, this);
    e.currentTarget.setPosition(pos);
  }

  onCirCleUp(e) {
    e.currentTarget.off(cc.Node.EventType.TOUCH_END, this.onCirCleUp, this);
    e.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL, this.onCirCleUp, this);
    let colorStr = "#00DBFF";
    if (e.currentTarget.name == "circle3") {
      colorStr = "#8F57FC";
    }
    e.currentTarget.color = new cc.Color().fromHEX(colorStr);
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
  }

  onMove(touch) {
    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);
    this.mouseNode.active = true;
    this.mouseNode.setPosition(pos);

    if (gameCtr.ins.isMoveTriangle) {
      this.triNode.active = true;
    } else {
      this.triNode.active = false;
    }
    /**
     * 判断与兵营子元素是否相交
     */
    let childs = this.barracks.children;
    this.descNode.active = false;
    for (let i = 0; i < childs.length; i++) {
      let dis = Math.sqrt(Math.pow(this.mouseNode.x - childs[i].x, 2) + Math.pow(this.mouseNode.y - childs[i].y, 2));
      // console.log(dis, "dis")
      if (dis < 40 && gameCtr.ins.barracksArr[i]) {
        this.descNode.active = true;
        this.descNode.getComponent(descComp).drawUi(gameCtr.ins.barracksArr[i], childs[i].getPosition());
        break;
      }
    }

    if (!gameCtr.ins.isFire) return;

    childs = this.eleNode.children;

    for (let i = 0; i < childs.length; i++) {
      let ele: cc.Node = childs[i];
      // console.log("hurtBlood");
      if (!ele) {
        // console.log("hurtBlood");
        continue;
      }

      let spr = ele.getComponent(BaseEle);
      if (spr.type != soliderType.monster) continue;

      if (spr.isFire) continue;

      let dis = Math.sqrt(Math.pow(this.mouseNode.x - childs[i].x, 2) + Math.pow(this.mouseNode.y - childs[i].y, 2));
      // console.log(dis, "dis")
      if (dis < 20) {
        // let dir = 1;
        // SoundResManager.getInstance().Play("fire");
        spr.doFire(nowPos);
      }
    }
  }

  onUp(touch) {

    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);
    gameCtr.ins.isFire = false;
    if (this.timeHandler)
      clearTimeout(this.timeHandler);

    this.triNode.active = false;
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
    this.mouseNode.getComponent(mouseCom).playAni("mouseIdle");

    this.mouseNode.active = false;

    if (this.isPause) return;

    if (gameCtr.ins.isFire) return;

    /**
     * 判断与兵营子元素是否相交
     */
    let childs = this.eleNode.children;

    for (let i = 0; i < childs.length; i++) {
      let ele: cc.Node = childs[i];
      // console.log("hurtBlood");
      if (!ele) {
        // console.log("hurtBlood");
        continue;
      }

      if (ele.getComponent(BaseEle).type != soliderType.monster) continue;

      let dis = Math.sqrt(Math.pow(this.mouseNode.x - childs[i].x, 2) + Math.pow(this.mouseNode.y - childs[i].y, 2));
      // console.log(dis, "dis")
      if (dis < 20) {
        let dir = 1;
        SoundResManager.getInstance().Play("click");
        ele.getComponent(BaseEle).doFly(dir);
      }
    }
  }

  /**
   * 返回开始场景
   */
  onBack() {

    this.eleNode.removeAllChildren();
    this.resNode.removeAllChildren();
    this.circleNode.removeAllChildren();
    this.bloodLayer.removeAllChildren();

    robotPvpCtr.ins.isStart = false;

    this.readyNode.active = false;
    gameCtr.ins.monsterInter = 350;
    gameCtr.ins.resTime = 0;
    gameCtr.ins.dlNum = 0;
    this.unscheduleAllCallbacks();
    this.monsterTime = false;

    cc.find("loadNode").active = true;
    SceneManager.getInstance().loadScene("startScene", true, () => {
      cc.find("loadNode").active = false;
    });
  }

  update(dt) {

    if (!robotPvpCtr.ins.isStart) return;

    this.updatePlayer();

    if (this.resNode.children.length <= 0) {
      this.createPvpRes();
    }

    let now = new Date().getTime();
    if (robotPvpCtr.ins.gameOverTime < now && robotPvpCtr.ins.isStart) {
      this.doOver();
    }

    if (robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1).hp <= 0 && robotPvpCtr.ins.isStart) {
      this.doOver();
    }

    if (robotPvpCtr.ins.players.get(gameCtr.ins.roleId).hp <= 0 && robotPvpCtr.ins.isStart) {
      this.doOver();
    }

    // let robotState = robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1);

    // if (robotState.gold > 25) {
    //   this.createRobotDogs();
    // }

    let childs = this.eleNode.children;

    /**遍历英雄元素 */
    childs.forEach(ele => {
      if (ele && ele.getComponent(BaseEle)) {
        ele.getComponent(BaseEle).onFrameLoop(dt);
      }
    })

    this.bulletNode.children.forEach(ele => {
      if (ele) {
        if (ele.getComponent(bulletEle)) {
          ele.getComponent(bulletEle).move(dt)
        }
        if (ele.getComponent(arrowEle)) {
          ele.getComponent(arrowEle).move(dt)
        }
        if (ele.getComponent(fireBallEle)) {
          ele.getComponent(fireBallEle).move(dt)
        }

        if (ele.getComponent(recoverEle)) {
          ele.getComponent(recoverEle).move(dt)
        }

        if (ele.getComponent(snowEle)) {
          ele.getComponent(snowEle).move(dt)
        }
      }
    })
  }

  doOver() {
    let robotState = robotPvpCtr.ins.players.get(gameCtr.ins.roleId * -1);
    let playerState = robotPvpCtr.ins.players.get(gameCtr.ins.roleId);
    robotPvpCtr.ins.isStart = false;
    this.overNode.active = true;
    this.scheduleOnce(() => {
      this.onBack();
    }, 5)
    if (playerState.hp > robotState.hp) {
      netCtr.ins.integral(1);
      this.txt1.string = "+2积分";
      this.txt11.string = "你获得 胜利"
      this.txt2.string = "-2积分";
      this.txt22.string = robotState.nickName + "失败"
    } else {
      netCtr.ins.integral(2);
      this.txt1.string = "+2积分";
      this.txt11.string = robotState.nickName + "胜利"
      this.txt2.string = "-2积分";
      this.txt22.string = "你被打败";
    }
  }
}
